# Tagging bot
# by Cee Pee

import forumapi

def settings(settings):
	settings.add_option("-t", "--thread", type="int", help="thread ID to work on", metavar="ID")
	settings.add_option("--add", type="list", help="tags to add", metavar="TAGS")
	settings.add_option("--remove", type="list", help="tags to remove", metavar="TAGS")
	settings.add_option("--purge", help="tag to remove from all threads (ignores other options)", metavar="TAG")
	settings.add_option("--wipe", action="store_true", default=False, help="remove all tags from thread")
	settings.add_option("--auto-tag", action="store_true", default=False, help="add tags to thread based on its title")

def main(me, options, args):
	add_tags = options.add or []
	remove_tags = options.remove or []
	
	if options.thread is None and not options.purge:
		raise(forumapi.OptionError("No thread ID given!"))
	
	if options.purge:
		print("Deleting all instances of tag {0}".format(options.purge))
	else:
		print("Thread ID: {0}".format(options.thread))
	
	if options.purge:
		tag = me.module.get_attr("Tag").Tag(me, name=options.purge)
		for thread in tag.threads:
			print(repr(thread))
			thread.update_tags(remove=[tag])
	else:
		thread = forumapi.Thread(me, options.thread)
		print(repr(thread))
		
		if options.auto_tag:
			for word in thread.title.split(" "):
				suggestions = me.module.get_attr("Tag").get_tag_suggest(me, word)
				if suggestions:
					word = suggestions[0]
				elif len(word) < 4:
					# Probably useless
					continue
				
				add_tags.append(word)
		
		if options.wipe:
			remove_tags = list(thread.tags)
		
		thread.tags.update_tags(add=add_tags, remove=remove_tags)

if __name__ == "__main__":
	forumapi.run(main, options=settings, supported_types=["vbulletin"])
